//
//  HPBaseSwiper.m
//  HPZZTong
//
//  Created by wenjun on 14-5-7.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPBaseSwiper.h"
//#import "CategoryUtil.h"
//#import "HPClientEngine.h"

@interface HPBaseSwiper(){}
@property (strong,nonatomic) SwiperComplete completeBlock;
@property (strong,nonatomic) NSTimer * timeoutTimer;
@end

@implementation HPBaseSwiper

+ (id)sharedInstance { return nil; }
- (void)stopOperation{}
- (void)startOperation{}

- (id)initWithSwiperQueue:(dispatch_queue_t)swiperQueue wrapperQueue:(dispatch_queue_t)wrapperQueue
{
    self = [super init];
    _swiperQueue = swiperQueue;
    _wrapperQueue = wrapperQueue;
    _defaultTimeout = 60;
    _connectState = SwiperStateNoDeviceDected;
    return self;
}

- (id)init
{
    self = [super init];
    _defaultTimeout = 60;
    _connectState = SwiperStateNoDeviceDected;
    return self;
}

- (void)connectStateChanged:(SwiperState)connectState
{
    if (_connectState != connectState)
    {
        if (connectState < SwiperStateConnected)
        {
            _ksn = nil;
            if (connectState == SwiperStateNoDeviceDected)
            {
                if ([self hasOperation])
                {
                    [self operationFinishedWithResult:[HPSwiperResult failResultWithCode:HPSwiperResultNotConnected]];
                }
            }
        }
        [self willChangeValueForKey:@"connectState"];
        _connectState = connectState;
        [self didChangeValueForKey:@"connectState"];
    }
}

- (void)waitAudioConfig
{
    if (![self isBlueThooth] && _connectState == SwiperStateConnecting)
        [NSThread sleepForTimeInterval:2.5];
}

//同步刷卡器方法调用
- (void)doOperation:(OperationBlock)operation complete:(SwiperComplete)complete
{
    HPSwiperResultCode checkResult = [self checkSwiperOperation];
    if (checkResult == HPSwiperResultNone)
    {
        self.completeBlock = complete;
        [self startTimer:_defaultTimeout];
        
        dispatch_async(_wrapperQueue, ^
        {
            [self waitAudioConfig];
            dispatch_async(_swiperQueue,^
            {
                HPSwiperResult * returnResult = operation();
                if (returnResult)
                {
                    __block SwiperComplete completeBlock = _completeBlock;
                    [self clear];
                    dispatch_async(dispatch_get_main_queue(), ^
                    {
                        ExecuteSwiperBlock(completeBlock, returnResult);
                    });
                }
            });
        });
    }
    else
        ExecuteSwiperBlock(complete, [HPSwiperResult failResultWithCode:checkResult]);
}

- (BOOL)checkIsICCard:(NSDictionary*)dic{
    // marco changed
//    NSString* dgTrade = [HPCLIENTENG GetGlobalData:KEY_TRADE];
//    if ( dgTrade.length   /** ![NSString isNilOrEmpty:dgTrade] */
//        && [dgTrade isEqualToString:@"0"]) {
//        NSString* serviceCode = [dic objectForKey:@"serviceCode"];
//        if ( serviceCode.length /*![NSString isNilOrEmpty:serviceCode]*/) {
//            if([serviceCode hasPrefix:@"2"] || [serviceCode hasPrefix:@"6"]){
//                return YES;
//            }
//        }
//        
//    }

    return NO;
}

- (void)beginSwiperOperation:(NSInvocation *)invocation timeout:(NSTimeInterval)timeout complete:(SwiperComplete)complete
{
//    LOG(@"invocation %@",NSStringFromSelector(invocation.selector));
    [invocation retainArguments];
    HPSwiperResultCode checkResult = [self checkSwiperOperation];
    if (checkResult == HPSwiperResultNone)
    {
        self.completeBlock = complete;
        [self startTimer:timeout];
        dispatch_async(_wrapperQueue, ^
        {
            [self waitAudioConfig];
            dispatch_async(_swiperQueue, ^
            {
                [invocation invoke];
            });
        });
    }
    else
        [self operationFinishedWithResult:[HPSwiperResult failResultWithCode:checkResult]];
}

- (void)operationFinishedWithResult:(HPSwiperResult *)swiperResult
{
//    LOG(@"operationFinishedWithResult:%d",swiperResult.code);
    if (_connectState == SwiperStateConnecting && !swiperResult.isSuccess && swiperResult.code != HPSwiperResultLowBattery)
    {
        [self connectStateChanged:SwiperStateConnectFailed];
    }else if(_connectState == SwiperStateConnecting && swiperResult.code == HPSwiperResultLowBattery){
        [self connectStateChanged:SwiperStateLowBattery];
    }
    __block SwiperComplete completeBlock = _completeBlock;
    
    if (swiperResult.code != HPSwiperResultSelectApplication) {
        [self clear];
    }else{
    }
    if (completeBlock)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            completeBlock(swiperResult);
        });
    }
}

-(void)selectApp:(NSArray*)index time:(int)time factor:(NSString *)factor complete:(SwiperComplete)complete{ }

- (void)operationTimeout
{
//    LOG(@"operationTimeout");
    dispatch_async(_swiperQueue, ^
    {
        [self stopSwiper];
    });
    
    [NSThread sleepForTimeInterval:1.5];
    [self operationFinishedWithResult:[HPSwiperResult failResultWithCode:HPSwiperResultTimeout]];
}

- (void)startTimer:(NSTimeInterval)timeout
{
    dispatch_async(_wrapperQueue, ^
    {
        NSTimeInterval interval = timeout > 0 ? timeout : _defaultTimeout;
        _timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(operationTimeout) userInfo:nil repeats:NO];
    });
}

- (void)clear
{
//    LOG(@"clear");
    [self removeTimer];
    _completeBlock = nil;
}

- (void)removeTimer
{
    if (_timeoutTimer)
    {
        [_timeoutTimer invalidate];
        _timeoutTimer = nil;
    }
}

- (HPSwiperResultCode)checkSwiperOperation
{
    if (_connectState == SwiperStateNoDeviceDected || _connectState == SwiperStateConnectFailed)
    {
        return HPSwiperResultNotConnected;
    }
    else if ([self hasOperation])
    {
        return HPSwiperResultBusy;
    }
    return HPSwiperResultNone;
}

- (void)cancelSwiper
{
    [self removeTimer];
    
    dispatch_async(_wrapperQueue, ^{
        [self stopSwiper];
    });
    [self sleep:1.6];
}

- (void)cancelSwiperOperationWithCode:(HPSwiperResultCode)resultCode
{
    [self operationFinishedWithResult:[HPSwiperResult failResultWithCode:resultCode]];
    [self cancelSwiper];
}

- (void)cancelSwiperOperation
{
    [self cancelSwiperOperationWithCode:HPSwiperResultCancel];
}

- (void)stopSwiper
{
    [self clear];
    [self sleep:1.6];
}

- (BOOL)isConnected  { return NO; }
- (BOOL)hasOperation { return [_timeoutTimer isValid]; }
- (BOOL)isBlueThooth { return NO; }
- (BOOL)canInputPin { return NO; }

- (void)disconnect
{
    _ksn = nil;
    _connectState = SwiperStateNoDeviceDected;
}

- (void)sleep:(NSTimeInterval)time
{
    dispatch_async(_wrapperQueue, ^{
        [NSThread sleepForTimeInterval:time];
    });
}
@end
